import boto3

from framework.common.pt_logger import logger

sqs_client = boto3.client('sqs')
base_queue_url = "https://sqs.us-east-2.amazonaws.com/599885534814"

def create_if_not_existed(queue_name):
    queue_url = exists_queue(queue_name)
    if not queue_url:
        queue_url = create_sqs(queue_name)
    return queue_url

def create_sqs(queue_name):
    logger.info("creating queue_name: %s" % queue_name)
    response = sqs_client.create_queue(
        QueueName=queue_name,
        Attributes={
            'MessageRetentionPeriod': '1209600',  # MAX 14 days
            'VisibilityTimeout': '60'
        }
    )
    if response and response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        queue_url = response.get("QueueUrl", None)
        logger.info("created queue_url: %s" % queue_url)
        # max_number_of_messages = response.get("Attributes", dict()).get("MaximumMessageSize", None)
        return queue_url
    else:
        logger.warning("create queue failed...")
        return None

def delete_sqs(queue_name):
    queue_url = "%s/%s" % (base_queue_url, queue_name)
    logger.info("deleting queue_url: %s" % queue_url)
    response = sqs_client.delete_queue(
        QueueUrl=queue_url
    )
    if response and response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        logger.info("deleted queue_url: %s" % queue_url)
        return True
    else:
        logger.warning("delete queue failed...")
        return False

def exists_queue(queue_name):
    queue_urls = list_queues(queue_name)
    return queue_urls[0] if queue_urls is not None and len(queue_urls) > 0 else None
    # return queue_urls is not None and len(queue_urls) > 0

def list_queues(prefix):
    response = sqs_client.list_queues(
        QueueNamePrefix=prefix,
        MaxResults=10
    )
    if response and response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        queue_urls = response.get("QueueUrls", None)
        logger.info("listing queue_urls: %s" % queue_urls)
        # max_number_of_messages = response.get("Attributes", dict()).get("MaximumMessageSize", None)
        return queue_urls
    else:
        logger.warning("listing queue_urls failed...")
        return None

def check_sqs_remain_message_count(queue_name):
    response = sqs_client.get_queue_attributes(
        QueueUrl=queue_name,
        AttributeNames=['All'])
    if response and response["ResponseMetadata"]["HTTPStatusCode"] == 200:
        remaining_number_of_messages = response.get("Attributes", dict()).get("ApproximateNumberOfMessages", None)
        # max_number_of_messages = response.get("Attributes", dict()).get("MaximumMessageSize", None)
        return remaining_number_of_messages
    else:
        logger.warning("get queue attributes failed...")
        return None

if __name__ == "__main__":
    # resp = create_sqs("abcd")
    # print(resp)
    # resp = delete_sqs("https://sqs.us-east-2.amazonaws.com/599885534814/abcd")
    # print(resp)
    # count = check_sqs_remain_message_count("https://sqs.us-east-2.amazonaws.com/599885534814/pt-spider-queue")
    # print(count)
    # queues = list_queues("pt-spider-queue")
    # print(queues)
    queue_existed = exists_queue("pt-spider-queue-20201102")
    print(queue_existed)
